package com.briup.day22;

/**
 * @author ThinkBook
 */
public class Test03_AgeException {
    public static void main(String[] args) throws AgeOutRangeException {
        Student s1 = new Student();
        s1.setName("tom");
        s1.setAge(21);
        System.out.println("s1: " + s1);

        System.out.println("---------------");

        // 主动捕获异常
        try {
            Student s2 = new Student("Jack", 21);
            s2.setAge(80);
            System.out.println("s2: " + s2);
        }catch(AgeOutRangeException e) {
            e.printStackTrace();
        }

        System.out.println("main 即将结束!");
    }
}

//自定义学生类
class Student {
    private String name;
    private int age;

    //构造方法
    public Student() {
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    //年龄取值 [4,79]
    public void setAge(int age) throws AgeOutRangeException {
        if(age < 4 || age > 79) {
            //抛出 年龄异常 【继续抛出 编译时异常】
            throw new AgeOutRangeException("学生年龄不在正常范围内");
        }
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//自定义异常类【编译时异常】
class AgeOutRangeException extends Exception {
    //1.提供无参构造器
    public AgeOutRangeException() {}

    //2.提供String一参构造器
    public AgeOutRangeException(String msg) {
        super(msg);
    }

}
